import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/stock_quant_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/models/odoo/stock_quant.dart';
import 'package:flutter_admin/models/odoo/stores_requisition.dart';
import 'package:flutter_admin/models/odoo/stores_requisition_info.dart';
import 'package:flutter_admin/pages/common/cry/cry_all.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/pages/odoo/material/stores_requisition/stores_requisition_quantity.dart';
import 'package:flutter_admin/pages/odoo/material/stores_requisition/stores_requisition_relation_dialog.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:quiver/strings.dart';

class StoresRequisitionRelation extends StatefulWidget {
  StoresRequisition? storesRequisition;
  StoresRequisitionRelation({required this.storesRequisition, Key? key})
      : super(key: key);
  @override
  _StoresRequisitionRelationState createState() =>
      _StoresRequisitionRelationState();
}

class _StoresRequisitionRelationState extends State<StoresRequisitionRelation> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page = PageModel(orders: [
    OrderItemModel(column: 'create_date', asc: false),
  ]);
  StockQuant stockQuant = StockQuant();
  List<StockQuant> selectedList = [];
  // List<SelectOptionVO> locationIdList = [];

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    ResponseBodyApi res = await DynamicDataApi.getModels(
        model: "stock.location",
        key: 'comment',
        val: "YLK");
    if(res.success!&&res.data.length == 1){
      stockQuant.locationId = res.data[0]["id"].toString();
    }
    _query();
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          // CrySelect(
          //   label: '库房位置',
          //   width: 380,
          //   dataList: locationIdList,
          //   value: storesRequisitionInfo.locationId,
          //   onSaved: (v) => {storesRequisitionInfo.locationId = v},
          // ),
          CryInput(
            width: 160,
            label: '物料编码',
            value: stockQuant.productCode,
            onSaved: (v) {
              stockQuant.productCode = v;
            },
          ),
          CryInput(
            width: 160,
            label: '物理名称',
            value: stockQuant.productName,
            onSaved: (v) {
              stockQuant.productName = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      // actions: !isDisplayDesktop(context)
      //     ? [
      //         _operationList(),
      //       ]
      //     : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(
          label: Text('库房位置'),
        ),
        DataColumn(
          label: Text('物料编码'),
        ),
        DataColumn(
          label: Text('物料名称'),
        ),
        DataColumn(
          label: Text('规格型号'),
        ),
        DataColumn(
          label: Text('数量'),
        ),
        DataColumn(
          label: Text('单位'),
        ),
      ],
      getCells: (m) {
        StockQuant stockQuant =
            StockQuant.fromMap(m);
        return [
          DataCell(Text(stockQuant.locationName ?? '--')),
          DataCell(Text(stockQuant.productCode ?? '--')),
          DataCell(Text(stockQuant.productName ?? '--')),
          DataCell(Text(stockQuant.productDes ?? '--')),
          DataCell(Text(stockQuant.quantity != null
              ? stockQuant.quantity.toString()
              : '--')),
          DataCell(Text(stockQuant.productUomName ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(children: <Widget>[
      CryButtons.query(context, () => _query()),
      CryButtons.reset(context, () => _reset()),
    ]);
    var footerBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: S.of(context).confirm,
          onPressed: selectedList.length != 1 ? null :() {
            StockQuant stockQuant = selectedList[0];
            showDialog(
              context: context,
              builder: (BuildContext context) => Dialog(
                child: StoresRequisitionQuantity(
                  stockQuant: stockQuant,
                  parentId: widget.storesRequisition!.id
                ),
              ),
            ).then((v) {
              if (v != null) {
                _loadSelectVO();
              }
            });
          },
          iconData: Icons.done_outlined,
        ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        )
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      appBar: AppBar(
        leading: Builder(
          builder: (BuildContext context) {
            // final ScaffoldState? scaffold = Scaffold.maybeOf(context);
            final ModalRoute<Object?>? parentRoute = ModalRoute.of(context);
            final bool canPop = parentRoute?.canPop ?? false;

            if (canPop) {
              return BackButton();
            } else {
              return SizedBox.shrink();
            }
          },
        ),
        title: Text('领料单绑定'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          Wrap(
            children: [
              form,
              // isDisplayDesktop(context) ? form : Container(),
              Padding(
                padding: EdgeInsets.only(top: 24),
                // child: isDisplayDesktop(context) ? buttonBar : Container(),
                child: buttonBar,
              )
            ],
          ),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
      bottomNavigationBar: footerBar,
    );
    return result;
  }

  _reset() {
    stockQuant = StockQuant();
    formKey.currentState!.reset();
    _loadSelectVO();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await StockQuantOdooApi.page(data: {
      "page": page,
      "domainList": stockQuant.toDomainList(),
    });
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<StockQuant>((e) => StockQuant.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  // _search() {
  //   return showDialog(
  //     context: context,
  //     builder: (BuildContext context) => Dialog(
  //       child: StoresRequisitionRelationDialog(),
  //     ),
  //   ).then((v) {
  //     if (v != null) {
  //       stockQuant = v;
  //       _query();
  //     }
  //   });
  // }

  // _operationList() {
  //   return PopupMenuButton(
  //     onSelected: (dynamic v) {
  //       if (v == OperationType.query) {
  //         _search();
  //       }
  //     },
  //     itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
  //       PopupMenuItem<OperationType>(
  //         value: OperationType.query,
  //         child: ListTile(
  //           leading: const Icon(Icons.search),
  //           title: Text('查询'),
  //         ),
  //       ),
  //     ],
  //   );
  // }
}
